package br.com.sisa.controller;

import java.io.IOException;
import java.rmi.ServerException;
import java.sql.SQLException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.sisa.model.UsuarioDAO;
import br.com.sisa.model.UsuarioVO;

public class Login extends HttpServlet {
	
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServerException {
		this.processRequest(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServerException {
		this.processRequest(request, response);
	}

	public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServerException {
		response.setContentType("text/html;charset=UTF-8");

		UsuarioVO vo = new UsuarioVO();
		UsuarioDAO dao = new UsuarioDAO();

		vo.setLogin(request.getParameter("login"));
		vo.setSenha(request.getParameter("senha"));
		try {
			vo = dao.logar(vo.getLogin(), vo.getSenha());
			validaLogin(vo, request, response);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// VERIFICA OS DADOS E REDIRECIONA PARA O INICIO

	private void validaLogin(UsuarioVO vo, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		try {
			if (vo.getLogin().equals(request.getParameter("login"))) {
				response.sendRedirect("mainmenu.html");
			} else {
				response.sendRedirect("view/login.jsp?erro=1");
			}
		} catch (NullPointerException e) {
			// TODO: handle exception
		}
	}

}